package com.eascs.afterloan.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.eascs.admin.common.vo.O2oUpdateLoanExpireTimeEntity;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.afterloan.entity.DeclareSignEntity;
import com.eascs.afterloan.service.BankCardService;
import com.eascs.afterloan.service.DeclareSignService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.doc.excel.RowReadHandler;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.loan.form.O2oLoanForm;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.workflow.service.WorkFlowSumbitService;

@RestController
@RequestMapping("/rdeclare")
public class DeclareSignRestController {

	private static Logger log = LoggerFactory.getLogger(DeclareSignRestController.class);
	@Autowired
	DeclareSignService service;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	@Autowired
	private WorkFlowSumbitService workFlowSumbitService;
	@Autowired
	private BankCardService bankCardService;
	@Autowired
	private DeclareSignService declareSignService;

	@RequestMapping("/uploadExcel")
	public BaseRestResult<String> uploadExcel(@RequestParam(value = "file", required = false) MultipartFile file) {
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			ExcelApiHelper.readHandle(inputStream, new RowReadHandler() {
				@Override
				public void handle(int sheetIndex, int rowIndex, Object[] rowDatas) {
					service.checkJCBank(sheetIndex, rowIndex, rowDatas, 0);
				}
			});
		} catch (RuntimeException e) {
			String message = e.getMessage();
			log.info("导入Exception={}", message);
			String s[] = message.split(":");
			return BaseRestResult.warn(s[1]);
		}

		InputStream inputStream1 = null;
		try {
			inputStream1 = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			ExcelApiHelper.readHandle(inputStream1, new RowReadHandler() {
				@Override
				public void handle(int sheetIndex, int rowIndex, Object[] rowDatas) {
					service.checkJCBank(sheetIndex, rowIndex, rowDatas, 1);
				}
			});
		} catch (RuntimeException e) {
			String message = e.getMessage();
			log.info("导入Exception={}", message);
			String s[] = message.split(":");
			return BaseRestResult.warn(s[1]);
		}
		return BaseRestResult.buildClosestReloadResult();
	}

	@RequestMapping("/download")
	public BaseRestResult<String> download(HttpServletResponse httpServletResponse, HttpServletRequest request) {
		BaseRestResult<String> result = null;
		String url = "declare_modle.xls";// 下载模板的路径
		String file = DeclareSignRestController.class.getResource("/excelTemplate/" + url).getPath();
		OutputStream os = null;
		try {
			String outfile = "批量确认放款数据.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(file);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}

		return result;
	}

	@RequestMapping("/declare_detail")
	public BaseRestResult<String> declare_detail() {
		service.delete();
		return HtmlRestResult.popHtmlFragment("afterloan/declare_detail");
	}

	@RequestMapping("/declare_file")
	public BaseRestResult<String> queryBankLoanData() {
		SelectDataOption[] selectDataOptions = { null, null, null, null, new SelectDataOption("BANKTYPEO2O") };
		PageResult<Object[]> pageResult = service.queryByPageDeclareSign();
		String titles[] = { "贷款单号", "借款人姓名", "省区", "平台", "放款银行", "放款日期", "放款金额(万元)" };
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles);
		o2oPagingInfo.setBuildPagingNavigation(true);
		o2oPagingInfo.setFirstRenderColumnIndex(0);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setFormats(new Format[] { null, null, null, null, null, null, new DecimalFormat(",##0.00") });
		ViewContext.put("paginationInfo", o2oPagingInfo);
		return HtmlRestResult.html("afterloan/declare_file");
	}

	@RequestMapping("/udpate")
	public BaseRestResult<String> update() {
		List<DeclareSignEntity> queryList = service.queryList();
		if (queryList != null && queryList.size() > 0) {
			for (DeclareSignEntity declareSignEntity : queryList) {
				O2oLoanapplyEntity o2oloanapply = o2oLoanapplyService.findById(declareSignEntity.getLoanapplyNo());
				O2oLoanUserEntity loanUser = o2oLoanUserService.findById(o2oloanapply.getLoanId(), declareSignEntity.getLoanapplyNo());
				O2oLoanForm o2oloanForm = new O2oLoanForm();
				o2oloanForm.setBillCode(o2oloanapply.getBillCode());
				o2oloanForm.setApplyAmount(o2oloanapply.getLoanaMount());
				o2oloanForm.setLoanAmount(declareSignEntity.getAmount());
				o2oloanForm.setLoanRate(o2oloanapply.getLoanrate());
				o2oloanForm.setLoanerCard(loanUser.getDocumentNo());
				// o2oloanForm.setLoanBankCode(o2oloanapply.getBankLoanName());
				o2oloanForm.setLoanBankCode(declareSignEntity.getBankLoanName());
				String loanTerm = bankCardService.getBankTerm(o2oloanapply.getBillCode());
				int intloanTerm = 0;
				if(StringUtil.isNotBlank(loanTerm))
				{
					intloanTerm = Integer.parseInt(loanTerm);
				}
				o2oloanForm.setLoanTerm(intloanTerm);
				o2oloanForm.setLoanerName(loanUser.getUserFullName());
				SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
				o2oloanForm.setLoanDate(f.format(declareSignEntity.getLoanDate()));
				o2oloanForm.setDataType("2");
				o2oloanapply.setPaymentTime(declareSignEntity.getLoanDate());
				o2oloanapply.setBankAmount(declareSignEntity.getAmount());
				o2oloanapply.setInstrumentNumber(declareSignEntity.getContractNum());
				o2oloanapply.setWfType(StatusContexts.O2O_FK_END);
				o2oloanapply.setLoanFlg(StatusContexts.O2O_YES);
				// 修改放款银行，不会修改到内审送审银行
				// o2oloanapply.setBankLoanName(yhssForm.getBankLoanName());
				O2oUpdateLoanExpireTimeEntity updateLoanTime = new O2oUpdateLoanExpireTimeEntity();
				updateLoanTime.setLoanapplyNo(o2oloanapply.getLoanapplyNo());
				updateLoanTime.setLoanTime(com.eascs.common.util.DateUtils.formateStandDate(o2oloanForm.getLoanDate()));
				updateLoanTime.setTerm(o2oloanForm.getLoanTerm());
				updateLoanTime.setExpireTime();
				o2oloanapply.setEndBankDate(new java.sql.Date(updateLoanTime.getExpireTime().getTime()));
				workFlowSumbitService.updatePayment(o2oloanapply, o2oloanForm);
				//start
				declareSignService.timer(o2oloanapply, declareSignEntity.getBankLoanName());
				//end
			}
			return BaseRestResult.info("更新成功").andRefresh();
		} else {
			return BaseRestResult.warn("没有查询到导入数据");
		}
	}

}
